<?php
/*
 * 集成阿里云通信轻量级短信接口
 *
 * 2018/07/13
 */

namespace app\common\model;

use think\Db;
use think\Session;
use think\Model;

class Jhsms extends  Model
{
    //设置信息
    private $settings=[];

    public function __construct()
    {
        $this->settings = config('sms');
    }

    public function send_sms($type,$mobile)
    {   $check = $this->check($type,$mobile);
        if(!$check['code']){
            return $check;
        }

        $rand_code = rand(10000,99999);

        $sendUrl = $this->settings['send_url']; //短信接口的URL

        $smsConf = array(
            'key'       => $this->settings['app_key'], //您申请的APPKEY
            'mobile'    => $mobile, //接受短信的用户手机号码
            'tpl_id'    => $this->settings['template_id'], //您申请的短信模板ID，根据实际情况修改
            'tpl_value' =>'#code#='.$rand_code //您设置的模板变量，根据实际情况修改
        );

        $content = $this->juhecurl($sendUrl,$smsConf,1); //请求发送短信

        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                //状态为0，说明短信发送成功
                $this->save_sms($type,$mobile,$rand_code);
                return $this->return_success('短信发送成功');
            }else{
                //状态非0，说明失败
                $msg_r = $result['reason'];
                return $this->return_error("短信发送失败(".$error_code.")：".$msg_r);
            }
        }else{
            //返回内容异常，以下可根据业务逻辑自行修改
            return $this->return_error('请求发送短信失败');
        }
    }

    public function  check_sms($type,$mobile,$sms){

        if(empty($sms)){
            return $this->return_error('请输入验证码');
        }
        $sms_code = Session::get('SMS_'.$mobile, 'SESSION_'.$type);
        $dueTime = Session::get('DUE_TIME', 'SESSION_'.$type);
		if(empty($sms_code) || $dueTime < time()){
			return $this->return_error('无此验证码或已失效，请重新发送');
		}

		if($sms != $sms_code){
			return $this->return_error('验证码有误');
		}
        Session::clear('SESSION_'.$type);
		return $this->return_success('验证码验证成功');
    }

    public function save_sms($type,$mobile,$sms){
        Session::set('SMS_'.$mobile, $sms, 'SESSION_'.$type);
        // 存储过期时间
        Session::set('DUE_TIME', time() + $this->settings['effect_time'] * 60, 'SESSION_'.$type);
    }

    public function check($type,$mobile){
        if(!preg_match("/^1[345789]\d{9}$/", $mobile)){
            return $this->return_error('手机格式有误');
        }

        if($type != 'FORGET' && $type != 'REGIS' && $type != 'CHANGE'){
            return $this->return_error('无此类型验证码');
        }

        $sms_code = Session::get('SMS_'.$mobile, 'SESSION_'.$type);
        $dueTime = Session::get('DUE_TIME', 'SESSION_'.$type);

        if(empty($sms_code) || $dueTime < time()){
            //无验证码或已过期
            $exist = Db::name('user')->where('tel',$mobile)->find();
            if($type=='REGIS'||$type=='CHANGE'){
                //注册或绑定新的手机号 手机应不存在
                if($exist){
                    return $this->return_error('当前手机号已存在');
                }
            }else{
                if(!$exist){
                    return $this->return_error('当前手机号不存在');
                }
            }

            return $this->return_success('check success');
        }
        return $this->return_error('验证码已发送，'.$this->settings['effect_time'].'分钟内有效，请勿重复发送');
    }

    private function  return_success($msg){
        return ['code'=>1,'msg'=>$msg];
    }

    private function  return_error($msg){
        return ['code'=>0,'msg'=>$msg];
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    private function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }

}
